package com.innovation.chengzhangriji.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.TextView;

import com.google.gson.Gson;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.BabyAndParent;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.adapter.DiaryAdapter;
import com.innovation.chengzhangriji.ui.adapter.DiaryViewHolder;
import com.innovation.chengzhangriji.ui.agent.HomeActivityAgent;
import com.innovation.chengzhangriji.ui.widget.CuteButton;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.util.BabyUtil;

import java.util.ArrayList;
import java.util.HashMap;

public class ChZhRJFragment extends BaseFragment implements DiaryAdapter.DiaryAdapterAgent,CuteToolbar.OnClickCuteToolbarListener {

    private LinearLayout diaryLayout;

    private HomeActivityAgent agent;
    private Baby[] babies = new Baby[0];

    private CuteButton cuteButton_new,cuteButton_notice;

    private View topLineView, bottomLineView;
    private PopupWindow popupWindow;
    private LinearLayout linearlayout_forpop;
    private ImageView iv_new,iv_guanzhu;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(contentView == null) {
            contentView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_chzhrj, null);
            setLayout();
        }
        return contentView;
    }

    // 初始化视图
    private void setLayout() {
        CuteToolbar mToolbar = (CuteToolbar) contentView.findViewById(R.id.toolbar_czrj);
        mToolbar.setOnClickCuteToolbarListener(this);
        linearlayout_forpop = (LinearLayout) contentView.findViewById(R.id.linearlayout_forpop);
        // 日记列表
        diaryLayout = (LinearLayout) contentView.findViewById(R.id.diary_layout);
        // 上下边线
        topLineView = contentView.findViewById(R.id.top_line);
        bottomLineView = contentView.findViewById(R.id.bottom_line);

//        cuteButton_new = (CuteButton) contentView.findViewById(R.id.chzhrj_newriji);
//        cuteButton_new.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(),NewDiaryActivity.class);
//                startActivity(intent);
//            }
//        });
//        cuteButton_notice = (CuteButton) contentView.findViewById(R.id.chzhrj_guanzhu);
//        cuteButton_notice.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(),NoticeDiaryActivity.class);
//                startActivity(intent);
//            }
//        });
    }

    @Override
    public void onResume() {
        super.onResume();
        agent = ((HomeActivity)getActivity()).getAgent();
        // 刷新数据
        refreshData();
    }

    // 刷新数据
    public void refreshData() {
        DiaryAdapter diaryAdapter = new DiaryAdapter(this);
        babies = agent.getAllBabyList();
        diaryLayout.removeAllViews();
        if (babies.length > 0) {
            linearlayout_forpop.setBackgroundResource(R.color.theme_bg);
            topLineView.setVisibility(View.VISIBLE);
            bottomLineView.setVisibility(View.VISIBLE);
            for(int i = 0; i < babies.length; i++) {
                View itemView;
                if(viewMaps.containsKey(babies[i].getBabyID())) {
                    itemView = viewMaps.get(babies[i].getBabyID());
                } else {
                    itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_diary, null);
                    viewMaps.put(babies[i].getBabyID(), itemView);
                }
                diaryLayout.addView(itemView);
                DiaryViewHolder diaryViewHolder = new DiaryViewHolder(itemView, this);
                diaryAdapter.bindViewHolder(diaryViewHolder, i);
            }
        } else {
            topLineView.setVisibility(View.GONE);
            bottomLineView.setVisibility(View.GONE);
            linearlayout_forpop.setBackgroundResource(R.mipmap.rijinull);
        }
        System.out.println("baby-length:" + babies.length);
    }

    // 缓存部分View
    private HashMap<Integer, View> viewMaps = new HashMap<>();

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        viewMaps.clear();
    }

    @Override
    public String getBabyHeadUrl(int position) {
        String url = babies[position].getImageUrl();
        return TextUtils.isEmpty(url)? "" : url;
    }

    @Override
    public String getDiaryName(int position) {
        String noteName = babies[position].getNoteName();
        return TextUtils.isEmpty(noteName)? (babies[position].getName() + "的成长日记") : noteName;
    }

    @Override
    public String getBabyDay(int position) {
        return BabyUtil.getBabyDay(babies[position], System.currentTimeMillis());
    }

    @Override
    public int getBabySex(int position) {
        return babies[position].getGender();
    }

    @Override
    public boolean canWrite(int position) {
        return agent.getBabyAndParent(babies[position].getBabyID()).getPermission() != 0;
    }

    @Override
    public int getDiaryCount() {
        return babies.length;
    }

    @Override
    public void OnItemClick(int position) {
        Intent intent = new Intent(getContext(), DiscoverTimelineActivity.class);
        LoginInfo loginInfo = Config.getLoginInfo(getContext());
        loginInfo.setBabyID(babies[position].getBabyID());
        Config.setLoginInfo(getContext(), new Gson().toJson(loginInfo));
        getContext().startActivity(intent);
    }

    @Override
    public void onClickLeft() {

    }

    @Override
    public void onClickRight() {
        Log.e("asd","asd");
        int[] location = new int[2];
//        ParentActivity.this.relativeLayout.getLocationOnScreen(location);// 获得指定控件的坐标
        linearlayout_forpop.getLocationOnScreen(location);// 获得指定控件的坐标
        final View popupWindow_view = getActivity().getLayoutInflater().inflate(R.layout.pop_czrj, null, false);
        popupWindow = new PopupWindow(popupWindow_view, AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT, true);
        //新建
        iv_new = (ImageView) popupWindow_view.findViewById(R.id.iv_creatnew);
        iv_new.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                Intent intent = new Intent(getActivity(),NewDiaryActivity.class);
                startActivity(intent);
            }
        });
        //刷新
        iv_guanzhu = (ImageView) popupWindow_view.findViewById(R.id.iv_creatguanzhu);
        iv_guanzhu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                Intent intent = new Intent(getActivity(),NoticeDiaryActivity.class);
                startActivity(intent);
            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOnDismissListener(new poponDismissListener());
//                backgroundAlpha(0.5f);
//                frameLayout.setAlpha(0.5f);
//                linearLayout_H5.setAlpha(0.5f);

//        popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY, location[0], location[1] + relativeLayout.getHeight() - popupWindow.getHeight());
        popupWindow.showAtLocation(linearlayout_forpop, Gravity.NO_GRAVITY, location[0], location[1]+160);
    }
    /**
     * 添加新笔记时弹出的popWin关闭的事件，主要是为了防止连续触发2次以上的js
     * 造成弹出2个以上的popWin
     *
     * @author cg
     */
    class poponDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
                backgroundAlpha(1f);
        }
    }
    public void backgroundAlpha(float bgAlpha)
    {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getActivity().getWindow().setAttributes(lp);
    }
}
